package com.xc.quickstart.common.aspect;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.Instant;
import java.util.Date;

@Aspect
@Component
@Order(3)
@Slf4j
public class LogMethodAspect {

    @Pointcut("@annotation(com.xc.quickstart.common.annotation.LogAround)")
    private void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Instant begin = new Date().toInstant();

        log.debug("[LogMethodAspect]调用开始 args:{}", joinPoint.getArgs());

        Object proceed = joinPoint.proceed();
        String result = JSON.toJSONString(proceed);
        Instant end = new Date().toInstant();

        log.info("[LogMethodAspect]调用结束 args:{},response:{},cost:{},speed:{}"
                , joinPoint.getArgs()
                , JSON.toJSONString(result)
                , Duration.between(begin, end).toMillis()
                , Duration.between(begin, end).toMillis() > 500 ? "<<slow>>" : "<<fast>>");
        return proceed;
    }
}
